document.getElementById('send').addEventListener('click', () => {
  const msg = document.getElementById('msg').value
  chrome.runtime.sendMessage({ action: 'sendMessage', message: msg }, response => {
    document.getElementById('log').textContent = '消息已发送，等待回复...'
  })
})

// 监听 background 的结果
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'DOUBAO_RESULT') {
    document.getElementById('log').textContent = JSON.stringify(request.result, null, 2)
  }
})

document.getElementById('start').addEventListener('click', async () => {
  document.getElementById('log').textContent = '开始任务'

  for (let i = 0; i < 5; i++) {
    await fetch('http://127.0.0.1:3001/plugin/task', {})
      .then(res => res.json())
      .then(res => {
        chrome.runtime.sendMessage({ action: 'sendMessage', message: res.data.message }, response => {
          document.getElementById('log').textContent = `消息已发送，等待回复${i}`
        })
      })

    await new Promise(resolve => {
      setTimeout(resolve, 8000)
    })
  }
})
